<template>
  <div class="app-container">

    <!-- 查询条件 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="管理对象" prop="manageObject" v-if="showSearchField('manageObject')">
        <el-select v-model="queryParams.params.manageObject" placeholder="请选择管理对象" filterable size="small" @change="searchFieldChanged('manageObject', $event)">
          <el-option v-for="item in manageObjectOptions" :key="item.key" :label="item.label" :value="item.value" :disabled="item.disabled"></el-option>
        </el-select>
        <i class="el-icon-remove-outline" @click="toggleSearchShow('manageObject')"></i>
      </el-form-item>
      <el-form-item label="全文搜索" prop="searchValue" v-if="showSearchField('searchValue')">
        <el-select v-model="queryParams.searchValue" placeholder="请输入要检索的内容" clearable filterable remote size="small" @change="searchFieldChanged('searchValue', $event)">
          <el-option v-for="item in searchValueOptions" :key="item.key" :label="item.label" :value="item.value" :disabled="item.disabled"></el-option>
        </el-select>
        <i class="el-icon-remove-outline" @click="toggleSearchShow('searchValue')"></i>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="getList">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="searchFields"></right-toolbar>
      </el-form-item>
    </el-form>

    <!-- 应用、模块信息 -->
    <el-row :gutter="20">
      <el-col :xs="24" :sm="12" :md="8" :lg="6">
        <el-card class="box-card" v-if="application != null && false">
          <div slot="header" class="clearfix">
            <span>应用程序</span>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="searchFields"></right-toolbar>
          </div>
          <div v-if="application!=null">
            <ul class="list-group list-group-striped">
              <li class="list-group-item">
                <svg-icon icon-class="user" />应用名称
                <div class="pull-right">{{ application.name }}</div>
              </li>
              <li class="list-group-item">
                <svg-icon icon-class="phone" />应用描述
                <div class="pull-right">{{ application.description }}</div>
              </li>
              <li class="list-group-item">
                <svg-icon icon-class="email" />表前缀
                <div class="pull-right">{{ application.tablePrefix }}</div>
              </li>
              <li class="list-group-item">
                <svg-icon icon-class="tree" />包路径
                <div class="pull-right" v-if="application.orgList && application.orgList.length>0">{{ application.orgList[0].deptName }} / {{ postGroup }}</div>
              </li>
              <li class="list-group-item">
                <svg-icon icon-class="tree" />作者
                <div class="pull-right" v-if="application.orgList && application.orgList.length>0">{{ application.orgList[0].children[0].deptName }} / {{ postGroup }}</div>
              </li>
            </ul>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="8" :lg="6">
        <el-card class="box-card" v-if="module != null && false">
          <div slot="header" class="clearfix">
            <span>功能模块</span>
          </div>
          <div>
            <ul class="list-group list-group-striped">
              <li class="list-group-item">
                <svg-icon icon-class="user" />模块名称
                <div class="pull-right">{{ module.moduleName }}</div>
              </li>
              <li class="list-group-item">
                <svg-icon icon-class="phone" />应用描述
                <div class="pull-right">{{ module.moduleDescription }}</div>
              </li>
              <li class="list-group-item">
                <svg-icon icon-class="email" />模块前缀
                <div class="pull-right">{{ module.modulePrefix }}</div>
              </li>
              <li class="list-group-item">
                <svg-icon icon-class="tree" />包路径
                <div class="pull-right">{{ module.packageName }}</div>
              </li>
              <li class="list-group-item">
                <svg-icon icon-class="tree" />作者
                <div class="pull-right">{{ module.author }}</div>
              </li>
            </ul>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 头部工具条 -->
    <el-row :gutter="10" class="mb8" v-if="queryParams.params.manageObject==='application'">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['codegen:application:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['codegen:application:delete']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-download" size="mini" @click="handleExport"
                   v-hasPermi="['codegen:application:export']">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-upload" size="mini" @click="handleImportApplication"
                   v-hasPermi="['codegen:application:import']">导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-refresh" size="mini" @click="handleSyncDb" v-hasPermi="['codegen:application:sync']">同步</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <!-- 应用列表区 -->
    <el-table v-loading="loading" :data="applicationList" @selection-change="handleSelectionChange" v-if="queryParams.params.manageObject === 'application'">
      <el-table-column type="selection" align="center" width="50"></el-table-column>
      <el-table-column label="序号" type="index" width="50" align="center">
        <template #default="scope">
          <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
        </template>
      </el-table-column>
      <el-table-column label="id" align="center" prop="id" v-if="false"/>
      <el-table-column label="应用名称" align="center" prop="name" />
      <el-table-column label="应用描述" align="center" prop="description" />
      <el-table-column label="表前缀" align="center" prop="tablePrefix" />
      <el-table-column label="包路径" align="center" prop="packageName" />
      <el-table-column label="作者" align="center" prop="author" />
      <el-table-column label="依赖的应用" align="center" prop="dependentApplicationIds" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button type="text" size="small" icon="el-icon-open"     @click="handleOpenModule(scope.row)"  v-hasPermi="['codegen:module:view']"        >模块</el-button>
          <el-button type="text" size="small" icon="el-icon-open"     @click="handleOpenTable(scope.row)"   v-hasPermi="['codegen:table:view']"         >实体表</el-button>
          <el-button type="text" size="small" icon="el-icon-edit"     @click="handleEdit(scope.row)"        v-hasPermi="['codegen:application:edit']"   >编辑</el-button>
          <el-button type="text" size="small" icon="el-icon-delete"   @click="handleDelete(scope.row)"      v-hasPermi="['codegen:application:delete']" >删除</el-button>
          <el-button type="text" size="small" icon="el-icon-refresh"  @click="handleSyncDb(scope.row)"      v-hasPermi="['codegen:table:sync']"         >同步</el-button>
          <el-button type="text" size="small" icon="el-icon-download" @click="handleGen(scope.row)"         v-hasPermi="['codegen:application:gencode']">生成代码</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控制 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 查看、添加、修改对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="showDialog" width="800px" append-to-body>
      <el-form ref="form" :model="application" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="应用名称" prop="name">
              <el-input v-model="application.name" placeholder="请输入应用名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="应用描述" prop="description">
              <el-input v-model="application.description" placeholder="请输入应用描述" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="表前缀" prop="tablePrefix">
              <el-input v-model="application.tablePrefix" placeholder="请输入表前缀" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="包路径" prop="packageName">
              <el-input v-model="application.packageName" placeholder="请输入包路径" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="作者" prop="author">
              <el-input v-model="application.author" placeholder="请输入作者" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="lombok 模式">
              <el-checkbox v-model="application.entityLombokModel"></el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="MyBatis-Plus 模式">
              <el-checkbox v-model="application.mybatisPlusModel"></el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="微服务 模式">
              <el-checkbox v-model="application.microServiceModel"></el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="使用 Swagger">
              <el-checkbox v-model="application.useSwagger"></el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="Spring Boot 版本" prop="springBootVersion">
              <el-input v-model="application.springBootVersion" placeholder="请输入 Spring Boot 版本" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="Flyway 版本" prop="flywayMigrationVersion">
              <el-input v-model="application.flywayMigrationVersion" placeholder="请输入 Flyway 版本" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="前后端分离">
              <el-checkbox v-model="application.frontendBackendSplitting"></el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="读写分离">
              <el-checkbox v-model="application.readWriteSplitting"></el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="依赖的应用">
              <el-select v-model="application.dependentApplicationIds" multiple placeholder="请选择应用">
                <el-option
                  v-for="item in applicationList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="模块列表" prop="moduleList"/>
            <!-- 主要列表  -->
            <el-table v-loading="loading" :data="application.moduleList">
              <el-table-column type="selection" width="45" align="center">
                <template #default="scope">
                  <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
                </template>
              </el-table-column>
              <el-table-column label="id" align="center" prop="id" v-if="false"/>
              <el-table-column label="应用ID" align="center" prop="applicationId" v-if="false" />
              <el-table-column label="模块名称" align="center" prop="moduleName" />
              <el-table-column label="模块描述" align="center" prop="moduleDescription" />
              <el-table-column label="排序编号" align="center" prop="orderNum" />
              <el-table-column label="模块前缀" align="center" prop="modulePrefix" />
              <el-table-column label="包路径" align="center" prop="packageName" />
              <el-table-column label="作者" align="center" prop="author" />
              <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template #default="scope">
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-open"
                    @click="handleOpen(scope.row)"
                    v-hasPermi="['codegen:application:view']"
                  >打开</el-button>
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-view"
                    @click="handleView(scope.row)"
                    v-hasPermi="['codegen:application:view']"
                  >查看</el-button>
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-edit"
                    @click="handleEdit(scope.row)"
                    v-hasPermi="['codegen:application:edit']"
                  >修改</el-button>
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-delete"
                    @click="handleDelete(scope.row)"
                    v-hasPermi="['codegen:application:delete']"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="showDialog = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 代码生成对话框 -->
    <el-dialog :title="codeGenConfig.title" :visible.sync="codeGenConfig.open" width="800px" append-to-body>
      <el-form ref="codeGenConfigForm" :model="codeGenConfig.form" :rules="rules" label-width="110px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="应用名称" prop="applicationId">
              <el-select v-model="codeGenConfig.form.applicationId" >
                <el-option v-for="item in applicationList" :key="item.id" :label="item.description" :value="item.id" :disabled="true"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="应用相关" prop="genApplicationCode">
              <el-checkbox v-model="codeGenConfig.form.genApplicationCode" /> 生成应用相关代码
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="模块相关" prop="genModuleCode">
              <el-checkbox v-model="codeGenConfig.form.genModuleCode" /> 生成模块相关代码
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="业务相关" prop="genBusinessCode">
              <el-checkbox v-model="codeGenConfig.form.genBusinessCode" /> 生成业务相关代码
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="实体相关" prop="genEntityCode">
              <el-checkbox v-model="codeGenConfig.form.genEntityCode" /> 生成实体相关代码
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="实体映射表" prop="genMapperCode">
              <el-checkbox v-model="codeGenConfig.form.genMapperCode" /> 生成实体映射表
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleCodeGenConfig">确 定</el-button>
        <el-button @click="codeGenConfig.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 代码生成预览 -->
    <el-dialog :title="preview.title" :visible.sync="preview.open" width="80%" top="5vh" append-to-body class="scrollbar">
      <el-tabs v-model="preview.activeName">
        <el-tab-pane v-for="(value, key) in preview.data"
          :label="key.substring(key.lastIndexOf('/')+1,key.indexOf('.vm'))"
          :name="key.substring(key.lastIndexOf('/')+1,key.indexOf('.vm'))" :key="key">
          <el-link :underline="false" icon="el-icon-document-copy" v-clipboard:copy="value"
            v-clipboard:success="clipboardSuccess" style="float:right">复制</el-link>
          <pre><code class="hljs" v-html="highlightedCode(value, key)"></code></pre>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>

    <!-- 数据导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的{{this.pageModelConfig.label}}数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="exportTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<style>
  .el-input {
    width: 220px;
  }
</style>

<script>
  import {
    searchChanged,
    listApplication,
    getApplication,
    getNew,
    addApplication,
    updateApplication,
    delApplication,
    syncDb
  } from "@/api/tool/gen/application";
  import { useRouter } from 'vue-router';

  // import hljs from "highlight.js/lib/highlight";
  // import "highlight.js/styles/github-gist.css";
  // import { option } from "runjs";
  import {getToken} from "@/utils/auth";
  // hljs.registerLanguage("java", require("highlight.js/lib/languages/java"));
  // hljs.registerLanguage("xml", require("highlight.js/lib/languages/xml"));
  // hljs.registerLanguage("yml", require("highlight.js/lib/languages/yaml"));
  // hljs.registerLanguage("html", require("highlight.js/lib/languages/xml"));
  // hljs.registerLanguage("vue", require("highlight.js/lib/languages/xml"));
  // hljs.registerLanguage("javascript", require("highlight.js/lib/languages/javascript"));
  // hljs.registerLanguage("sql", require("highlight.js/lib/languages/sql"));
  const router = useRouter();

  export default {
    name: "Gen",
    components: {
    },
    data() {
      return {
        // 版本号
        version: "1.4.36",
        loading: true,
        // 唯一标识符
        uniqueId: "",
        // 选中数组
        applicationIds: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 全文检索
        searchValue: [],
        // 可搜索选项
        searchValueOptions: [
        ],
        // 数据源列表
        datasourceList: [],
        // 应列表
        applicationList: [],
        // 表数据
        tableList: [],
        // 当前模块
        module: undefined,
        // 搜索字段信息
        searchFields: [
        ],
        // 列信息
        columns: [
          { key: 'name'         , label: `应用名称`  , visible: true  },
          { key: 'description'  , label: `应用描述`  , visible: true },
          { key: 'tablePrefix'  , label: `表前缀`    , visible: true },
          { key: 'packageName'      , label: `包路径`   , visible: true },
          { key: 'author'   , label: `作者` , visible: true },
          { key: 'entityLombokModel'     , label: `实体是否使用lombok模式` , visible: true },
          { key: 'mybatisPlusModel'     , label: `数据访问是否使用MyBatis-Plus模式` , visible: true },
          { key: 'microServiceModel'     , label: `微服务版模式` , visible: true },
          { key: 'createTime'     , label: `创建时间` , visible: true },
          { key: 'updateTime'     , label: `更新时间` , visible: true },
        ],
        // 管理对象
        manageObjectOptions: [
          {key:"datasource", value:"datasource", label: "数据源"},
          {key:"application", value:"application", label: "应用程序"},
          {key:"module", value:"module", label: "功能模块"},
          {key:"table", value:"table", label: "业务实体表"},
        ],
        // 待选应用列表
        applicationIdOptions: [],
        // 待选模块列表
        moduleIdOptions: [],
        // 待选数据源
        datasourceOptions: [],
        // 待选数据库
        tableSchemaOptions: [],
        // 待选表名
        tableNameOptions: [],
        // 表注解待选项
        tableCommentOptions: [],
        // 日期范围
        dateRange: "",
        // 页面模型配置
        pageModelConfig:{
          // 模块
          moduleName: "gen",
          moduleLabel: "代码生成",
          businessName: "application",
          businessLabel: "应用管理",
          name: "application",
          label: "应用",
          // 基本字体尺寸
          fontSize: 16,
          labelWidth: "68px",
          // 标签栏字符数(全角)
          labelSize: 6,
          searchColumns: [
          ],
          searchColumnsOptions: {},
          columns:[
          ],
          columnsOptions: {"datasource": [{
              "key": null,
              "value": "pandamimi-cloud",
              "label": "pandamimi-cloud",
              "disabled": null
            }]}
        },
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,

          applicationId: 0,
          moduleId: 0,
          tableName: '',
          tableComment: '',
          params: {
            manageObject: "application",
            changedField: null
          }
        },
        application: {
          name: undefined,
        },
        dialogTitle: '',
        showDialog: false,
        // 表单校验
        rules: {
        },
        // 数据导入参数
        upload: {
          // 是否显示弹出层（数据导入）
          open: false,
          // 弹出层标题（数据导入）
          title: "",
          // 是否禁用上传
          isUploading: false,
          // 是否更新已经存在的数据
          updateSupport: 0,
          // 设置上传的请求头部
          headers: { Authorization: "Bearer " + getToken() },
          // 上传的地址
          url: import.meta.env.VUE_APP_BASE_API + "/" + "code" + "/" + "application" + "/"+ "importData"
        },
        //
        codeGenConfig: {
          open: false,
          title: "代码生成配置",
          genType: undefined,
          genPath: undefined,
          form: {
            applicationId: undefined,

            /**
             * 生成应用相关代码
             */
            genApplicationCode: true,

            /**
             * 生成模块相关代码
             */
            genModuleCode: true,

            /**
             * 生成业务相关代码
             */
            genBusinessCode: true,

            /**
             * 生成实体表相关代码
             */
            genEntityCode: true,

            /**
             * 生成实体映射文件
             */
            genMapperCode: true,

          },
        },
        // 预览参数
        preview: {
          open: false,
          title: "代码预览",
          data: {},
          activeName: "domain.java"
        }
      };
    },
    created() {
      // 收集查询参数，默认均以 params 下的通用参数方式提交
      Object.keys(this.$route.query).forEach(key => {
        // 检查 key 是否是我们想要特别处理的参数
        if (key === 'pageNum' || key === 'applicationId') {
          // 对这些参数进行特别处理，比如转换为数字
          this.queryParams[key] = Number(this.$route.query[key]);
        } else if (!(key in this.queryParams)) {
          // 如果 key 不在我们已知的 queryParams 属性中，则将其添加到 params 对象中
          // 注意：这里我们假设 this.queryParams.params 已经是一个对象
          this.queryParams.params[key] = this.$route.query[key];
        }
        // 注意：我们没有对 't' 进行特别处理，因为它会被上面的 else if 语句捕获并添加到 params 中
      });
      // 初始化搜索字段
      this.searchFieldChanged();
    },
    activated() {
      const time = this.$route.query.t;
      if (time != null && time !== this.uniqueId) {
        this.uniqueId = time;
        this.getList();
      }
    },
    mounted() {
      this.$nextTick(() => {
        const formItems = this.$refs.queryForm.fields;
        formItems.forEach(item => {
          // 检查此字段是否已存在于 searchFields 中
          const existingField = this.searchFields.find(field => field.key === item.prop);
          if (!existingField) {
            // 如果不存在，则添加新字段
            this.searchFields.push({
              key: item.prop,
              label: item.label,
              visible: true
            });
          }
        });
      });
    },
    computed: {
    },
    methods: {
      // 是否显示指定搜索字段
      showSearchField(field) {
        let isShow = true;
        if(this.searchFields){
          let item = this.searchFields.find(item => item.key === field);
          if(item){
            isShow = item.visible;
          }
        }
        return isShow;
      },
      // 是否显示指定列表字段
      showListField(field) {
        let isShow = true;
        if(this.columns){
          let item = this.columns.find(item => item.key === field);
          if(item){
            isShow = item.visible;
          }
        }
        return isShow;
      },
      toggleSearchShow(field) {
        let searchField = null;
        if(Number.isInteger(field)){
          searchField = this.searchFields[field].key;
        }else{
          for(let i=0;i<this.searchFields.length;i++){
            if(this.searchFields[i].key===field){
              searchField = this.searchFields[i];
              break;
            }
          }
        }
        if(searchField){
          searchField.visible = !searchField.visible; // 切换显示状态
          console.log("调试：searchField="+searchField.key);
        }
      },
      // 搜索字段改变
      searchFieldChanged(changedField, value) {
        if(changedField === 'manageObject'){
          if(value !== 'table'){
            // 非当前业务，直接跳转目标页面
            router.push({"path":"/tool/gen/"+value});
          }else{
            changedField = null;
            this.queryParams
          }
        }

        this.queryParams.params['width'] = window.innerWidth;
        this.queryParams.params['height'] = window.innerHeight;

        let queryParams = this.addDateRange(this.queryParams, this.dateRange);
        queryParams.params.searchPropertyList = Object.keys(this.queryParams).filter(prop => !['pageSize', 'pageNum', 'params'].includes(prop));

        if(changedField!=null&&changedField!==""){
          queryParams.params.changedField = changedField;
        }

        if (changedField === 'manageObject') {
          this.queryParams.params.manageObject = value;
        }
        if(this.queryParams.params.manageObject === 'application'){
          searchChanged(queryParams).then(res => {
            this.application = {...res.data};

            // 如果检索条件验证通过，刷新列表
            if(res.data.params.searchValid){
              this.getList();
            }
          });
          if (changedField === 'applicationId' && value) {
            let param = {applicationId: value};
            const query = { ...this.$route.query, ...param };
            this.$router.replace({ path: this.$route.path, query });
          }
        }else if(this.queryParams.params.manageObject === 'module'){
          router.push({"path":"/tool/gen/module"});
        }else if(this.queryParams.params.manageObject === 'datasource'){
          router.push({"path":"/tool/gen/datasource"});
        }else if(this.queryParams.params.manageObject === 'table'){
          router.push({"path":"/tool/gen/table"});
        }else{
          this.loading = false;
          alert("调试：切换到业务实体管理！changedField = "+changedField+" , value = " + value);
        }
      },
      /** 查询表集合 */
      getList() {
        this.loading = true;
        if(this.queryParams.params.manageObject=='table'){
          let queryParams = this.addDateRange(this.queryParams, this.dateRange);
          listTable(queryParams).then(response => {
            this.tableList = response.rows;
            this.total = response.total;
            this.loading = false;
          });
        }else if(this.queryParams.params.manageObject=='application'){
          let queryParams = this.addDateRange(this.queryParams, this.dateRange);
          listApplication(queryParams).then(response => {
            this.applicationList = response.rows;
            this.total = response.total;
            this.loading = false;
          });
        }else if(this.queryParams.params.manageObject=='datasource'){
          listDatasource(this.queryParams).then(response => {
            this.datasourceList = response.rows;
            this.total = response.total;
            this.loading = false;
          });
        }
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.application.id != null) {
              updateApplication(this.application).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.showDialog = false;
                this.getList();
              });
            } else {
              addApplication(this.application).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.showDialog = false;
                this.getList();
              });
            }
          }
        });
      },
      cancel(){
        this.showDialog = false;
      },
      // 表单重置
      resetApplication() {
        this.application = {
          name: undefined,
          displayName: undefined,
          userName: undefined,
          password: undefined,
        };
        this.resetForm("applicationForm");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 新增应按钮操作 */
      handleAdd() {
        this.resetApplication();
        getNew().then(response => {
          this.showDialog = true;
          this.title = "添加应用";
          this.application = response.data;
        });
      },
      /** 打开按钮操作 */
      handleOpenModule(row) {
        router.push({path:'/tool/gen/module?applicationId='+row.id})
      },
      /** 打开按钮操作 */
      handleOpenTable(row) {
        router.push("/tool/gen/" + row.id);
        // router.push({path:'/tool/gen/table?applicationId='+row.id})
      },
      /** 修改按钮操作 */
      handleEdit(row) {
        let applicationId;
        if(row.id === null){
          applicationId = this.applicationIds;
        }else{
          applicationId = row.id;
        }
        getApplication(applicationId).then(response => {
          this.application = response.data;
          this.showDialog = true;
          this.dialogTitle = "修改应用";
        });
      },
      /** 同步数据库操作 */
      handleSyncDb(row) {
        let ids = [];
        if(row){
          ids.push(row.id)
        } else {
          ids = this.applicationIds;
        }
        if (ids.length===0) {
          this.$modal.msgError("请选择要同步的应用！");
          return;
        }
        let selectedApps = this.applicationList.filter(app => ids.includes(app.id));
        // 收集被选中的应用的名称
        let selectedAppNames = selectedApps.map(app => (app.description||app.name));

        // 构造提示信息
        let applicationName;
        if (selectedAppNames.length === 1) {
          applicationName = selectedAppNames[0];
        } else {
          // 如果选择了多个应用，使用它们的名称构造提示信息
          applicationName = selectedAppNames.join(', ');
          // 如果选中的应用超过一定数量（比如3个），可以在提示信息中添加省略号
          if (selectedAppNames.length > 3) {
            applicationName = selectedAppNames.slice(0, 3).join(', ') + ' 等'+ids.length+'个应用';
          }
        }
        this.$modal.confirm('确认要强制同步应用 ' + applicationName + ' 的数据结构吗？').then(function() {
          return syncDb(ids);
        }).then(() => {
          this.$modal.msgSuccess("同步成功");
        }).catch(() => {});
      },
      /** 生成代码操作 */
      handleGen(row) {
        this.codeGenConfig.form.applicationId = row.id;
        this.codeGenConfig.open = true;
        this.codeGenConfig.genType = row.genType;
        this.codeGenConfig.genPath = row.genCode;
      },
      /** 生成代码操作 */
      handleCodeGenConfig() {
        if (this.codeGenConfig.genType === "1") {
          genCode(this.applicationIds).then(response => {
            this.$modal.msgSuccess("成功生成到自定义路径：" + this.codeGenConfig.genPath);
          });
        } else {
          this.$download.zip("/code/application/genCode", "pandamimi", this.codeGenConfig.form);
        }
        this.codeGenConfig.open = false;
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('code/application/export', {
          ...this.queryParams
        }, `${this.pageModelConfig.label}数据_${new Date().getTime()}.xlsx`)
      },
      /** 打开导入表弹窗 */
      handleImportApplication() {
        this.upload.title = "数据导入";
        this.upload.open = true;
      },
      // 文件上传中处理
      handleFileUploadProgress(event, file, fileList) {
        this.upload.isUploading = true;
      },
      // 文件上传成功处理
      handleFileSuccess(response, file, fileList) {
        this.upload.open = false;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
        this.getList();
      },
      // 提交上传文件
      submitFileForm() {
        this.$refs.upload.submit();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.dateRange = [];
        this.resetForm("queryForm");
        this.handleQuery();
      },
      /** 预览按钮 */
      handlePreview(row) {
        previewTable(row.id).then(response => {
          this.preview.data = response.data;
          this.preview.open = true;
          this.preview.activeName = "domain.java";
        });
      },
      /** 高亮显示 */
      highlightedCode(code, key) {
        const vmName = key.substring(key.lastIndexOf("/") + 1, key.indexOf(".vm"));
        var language = vmName.substring(vmName.indexOf(".") + 1, vmName.length);
        const result = hljs.highlight(language, code || "", true);
        return result.value || '&nbsp;';
      },
      /** 复制代码成功 */
      clipboardSuccess() {
        this.$modal.msgSuccess("复制成功");
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.applicationIds = selection.map(item => item.id);
        this.single = selection.length !== 1;
        this.multiple = !selection.length;
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const applicationIds = row.id || this.applicationIds;
        let promptMsg = '是否确认删除名为"' + row.tableName + '"的数据项？';
        if (applicationIds.length > 1) {
          promptMsg = '是否确认删除这 ' + applicationIds.length + ' 项数据项？';
        }
        this.$modal.confirm(promptMsg).then(function() {
          return delApplication(applicationIds);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      /** 导出模板操作 */
      exportTemplate() {
        this.download('tool/gen/application/exportTemplate', {
        }, `${this.pageModelConfig.label}数据(模板)_${new Date().getTime()}.xlsx`)
      }
    }
  };
</script>
